package br.com.iswe.core.web.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;

import br.com.iswe.core.exp.ISWEException;
import br.com.iswe.core.facade.FacadeContract;

@SuppressWarnings("unchecked")
public class ServiceLocatorList implements ServiceLocator {

	private List<ServiceLocator> locators = new ArrayList<ServiceLocator>();
	
	private Log log = LogFactory.getLog(this.getClass());
	
	
	public Converter getConverter(Class bean) {
		return getConverter(bean.getName());
	}
	public Converter getConverter(String className){
		//varre a lista de converter locators
		ISWEException lastException = null;
		for(ServiceLocator locator : locators){
			try{
				//tenta obter o objeto
				Converter converter = ((BasicServiceLocator)locator).getConverter(className, false);
				if(converter != null){
					return converter;
				}
			}
			catch(ISWEException exp){
				lastException = exp;
			}
		}
		//caso tenha gerado alguma execao
		if(lastException != null){
			if(log.isErrorEnabled()){
				log.error("ServiceLocatorList : Problemas ao obter o converter para o bean: " + className + " ConverterLocators: " + locators.toString(), lastException);
			}
			//manda pra cima
			throw lastException;
		}
		return null;
	}

	public List<ServiceLocator> getLocators() {
		return locators;
	}

	public void setLocators(List<ServiceLocator> locators) {
		this.locators = locators;
	}

	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		//Nao preciso aqui da BeanFactory
	}
	
	@Override
	public FacadeContract getFacade(Class bean) {
		return getFacade(bean.getName());
	}
	public FacadeContract getFacade(String className){
		//varre a lista de converter locators
		ISWEException lastException = null;
		for(ServiceLocator locator : locators){
			try{
				//tenta obter o objeto
				FacadeContract facade = ((BasicServiceLocator)locator).getFacade(className, false);
				if(facade != null){
					return facade;
				}
			}
			catch(ISWEException exp){
				lastException = exp;
			}
		}
		//caso tenha gerado alguma execao
		if(lastException != null){
			if(log.isErrorEnabled()){
				log.error("ServiceLocatorList : Problemas ao obter o converter para o bean: " + className + " ConverterLocators: " + locators.toString(), lastException);
			}
			//manda pra cima
			throw lastException;
		}
		return null;
	}
}
